package com.comleader.operator.service.strategy;

import static cn.hutool.core.util.CharsetUtil.CHARSET_GBK;
import static com.comleader.operator.common.constant.Constant.*;
import static com.comleader.operator.common.constant.DictConstant.*;
import static com.comleader.operator.common.enums.InspectStatusEnum.FAILED;
import static com.comleader.operator.common.enums.OperatorInspectTypeEnum.IOV_CARD;
import static com.comleader.operator.common.enums.StatisticsTypeEnum.NONCOMPLIANT;
import static com.comleader.operator.common.enums.StatisticsTypeEnum.UNREGISTER;
import static com.comleader.operator.common.util.DesensitizeEntityUtil.desensitizeIovCard;
import static com.comleader.operator.validate.CommonValidator.*;
import static com.comleader.operator.validate.IovCardValidator.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.comleader.operator.common.constant.GlobalVariables;
import com.comleader.operator.common.util.ExcelUtil;
import com.comleader.operator.common.util.OperatorObjectUtil;
import com.comleader.operator.core.exception.BusinessException;
import com.comleader.operator.pojo.dto.IovCardStatDTO;
import com.comleader.operator.pojo.entity.InspectRecordEntity;
import com.comleader.operator.pojo.entity.InspectReportEntity;
import com.comleader.operator.pojo.entity.IovCardEntity;
import com.comleader.operator.service.InspectRecordService;
import com.comleader.operator.service.InspectReportService;
import com.comleader.operator.service.IovCardService;
import com.comleader.operator.service.OperatorInspectService;
import com.comleader.operator.validate.IovCardValidator;
import com.comleader.operator.validate.ValidateRule;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @Dscription
 * @Author 连新景
 * @Date 2024/07/29 16:49
 */
@AllArgsConstructor
@Slf4j
@Service
public class IovCardInspect implements InspectStartegy {

    private final InspectRecordService inspectRecordService;

    private final InspectReportService inspectReportService;

    private final IovCardService iovCardService;

    private final OperatorInspectService operatorInspectService;

    // 公共规则列表
    private static final List<ValidateRule<IovCardEntity>> commonRuleList = new ArrayList<>();
    // 个人规则列表
    private static final List<ValidateRule<IovCardEntity>> personalRuleList = new ArrayList<>();
    // 单位规则列表
    private static final List<ValidateRule<IovCardEntity>> companyRuleList = new ArrayList<>();

    @PostConstruct
    public void init() {
        commonRuleList.add(new ValidateRule<>("301", "格式异常数据", IovCardValidator::isFormatException, null));
        // 字段异常单独校验，因为缺失字段无法映射到对象上
        // validateRuleList.add(new ValidateRule<>("102", "字段异常数据", null));
        commonRuleList.add(new ValidateRule<>("303", "不在网状态", data -> !isDictIncorrect(IOVCARD_NOT_NET_STATE, data.getNumberStatus()), null));

        personalRuleList.add(new ValidateRule<>("304", "已售-个人用户-购卡渠道类型不合规", data -> isChannelTypeNoncompliant(data.getChannelType()), NONCOMPLIANT));
        personalRuleList.add(new ValidateRule<>("305", "已售-个人用户-购卡单位信息未登记", IovCardValidator::isCompanyUnregister, UNREGISTER));
        personalRuleList.add(new ValidateRule<>("306", "已售-个人用户-购卡责任人信息未登记", IovCardValidator::isPicUnregister, UNREGISTER));
        personalRuleList.add(new ValidateRule<>("307", "已售-个人用户-购卡经办人未登记", IovCardValidator::isAgentUnregister, UNREGISTER));
        personalRuleList.add(new ValidateRule<>("308", "已售-个人用户-购卡责任人&单位信息未登记", data -> isCompanyUnregister(data) && isPicUnregister(data), null));
        personalRuleList.add(new ValidateRule<>("309", "已售-个人用户-购卡责任人&经办人信息未登记", data -> isPicUnregister(data) && isAgentUnregister(data), null));
        personalRuleList.add(new ValidateRule<>("310", "已售-个人用户-购卡单位&经办人信息未登记", data -> isCompanyUnregister(data) && isAgentUnregister(data), null));
        personalRuleList.add(new ValidateRule<>("311", "已售-个人用户-购卡责任人&单位&经办人信息未登记",
            data -> isPicUnregister(data) && isCompanyUnregister(data) && isAgentUnregister(data), null));
        personalRuleList.add(new ValidateRule<>("312", "已售-个人用户-单位信息校验不合规", IovCardValidator::isCompanyNoncompliant, NONCOMPLIANT));
        personalRuleList.add(new ValidateRule<>("313", "已售-个人用户-购卡责任人信息校验不合规", IovCardValidator::isPicNoncompliant, NONCOMPLIANT));
        personalRuleList.add(new ValidateRule<>("314", "已售-个人用户-购卡经办人信息检验不合规", IovCardValidator::isAgentNoncompliant, NONCOMPLIANT));
        personalRuleList.add(new ValidateRule<>("315", "已售-个人用户-购卡责任人&单位信息校验不合规", data -> isPicNoncompliant(data) && isCompanyNoncompliant(data), null));
        personalRuleList.add(new ValidateRule<>("316", "已售-个人用户-购卡责任人&经办人信息校验不合规", data -> isPicNoncompliant(data) && isAgentNoncompliant(data), null));
        personalRuleList.add(new ValidateRule<>("317", "已售-个人用户-购卡单位&经办人信息校验不合规", data -> isCompanyNoncompliant(data) && isAgentNoncompliant(data), null));
        personalRuleList.add(new ValidateRule<>("318", "已售-个人用户-购卡责任人&单位&经办人信息校验不合规",
            data -> isPicNoncompliant(data) && isCompanyNoncompliant(data) && isAgentNoncompliant(data), null));
        personalRuleList.add(new ValidateRule<>("319", "已售-个人用户-购车用户（机主）证件类型未登记", data -> isUnregister(data.getOwnerIdType()), UNREGISTER));
        personalRuleList.add(new ValidateRule<>("320", "已售-个人用户-购车用户（机主）姓名未登记", data -> isUnregister(data.getOwnerName()), UNREGISTER));
        personalRuleList.add(new ValidateRule<>("321", "已售-个人用户-购车用户（机主）证件号码未登记", data -> isUnregister(data.getOwnerIdNumber()), UNREGISTER));
        personalRuleList.add(new ValidateRule<>("322", "已售-个人用户-购车用户（机主）证件地址未登记", data -> isUnregister(data.getOwnerIdAddress()), UNREGISTER));
        personalRuleList
            .add(new ValidateRule<>("323", "已售-个人用户-购卡使用户（机主）姓名&证件号码未登记", data -> isUnregister(data.getOwnerName(), data.getOwnerIdNumber()), null));
        personalRuleList
            .add(new ValidateRule<>("324", "已售-个人用户-购车用户（机主）姓名&证件地址未登记", data -> isUnregister(data.getOwnerName(), data.getOwnerIdAddress()), null));
        personalRuleList
            .add(new ValidateRule<>("325", "已售-个人用户-购车用户（机主）证件号码&证件地址未登记", data -> isUnregister(data.getOwnerIdNumber(), data.getOwnerIdAddress()), null));
        personalRuleList.add(
            new ValidateRule<>("326", "已售-个人用户-购车用户（机主）证件类型校验不合规", data -> isIdTypeNoncompliant(IOVCARD_IDCARD_TYPE, data.getOwnerIdType()), NONCOMPLIANT));
        personalRuleList.add(new ValidateRule<>("327", "已售-个人用户-购车用户姓名（机主）校验不合规", data -> isNameNoncompliant(data.getOwnerName()), NONCOMPLIANT));
        personalRuleList.add(new ValidateRule<>("328", "已售-个人用户-购车用户证件号码（机主）校验不合规",
            data -> isIdNumberNoncompliant(data.getOwnerIdType(), data.getOwnerIdNumber()), NONCOMPLIANT));
        personalRuleList.add(new ValidateRule<>("329", "已售-个人用户-购车用户（机主）证件地址校验不合规", data -> isAddressNoncompliant(data.getOwnerIdAddress()), NONCOMPLIANT));
        personalRuleList.add(new ValidateRule<>("330", "已售-个人用户-购车用户（机主）姓名&证件号码校验不合规",
            data -> isNameNoncompliant(data.getOwnerName()) && isIdNumberNoncompliant(data.getOwnerIdType(), data.getOwnerIdNumber()), null));
        personalRuleList.add(new ValidateRule<>("331", "已售-个人用户-购车用户（机主）姓名&证件地址校验不合规",
            data -> isNameNoncompliant(data.getOwnerName()) && isAddressNoncompliant(data.getOwnerIdAddress()), null));
        personalRuleList.add(new ValidateRule<>("332", "已售-个人用户-购车用户（机主）证件号码&证件地址校验不合规",
            data -> isIdNumberNoncompliant(data.getOwnerIdType(), data.getOwnerIdNumber()) && isAddressNoncompliant(data.getOwnerIdAddress()), null));
        personalRuleList.add(new ValidateRule<>("333", "已售-个人用户-购车用户（机主）姓名&证件号码&证件地址校验不合规", data -> isNameNoncompliant(data.getOwnerName())
            && isIdNumberNoncompliant(data.getOwnerIdType(), data.getOwnerIdNumber()) && isAddressNoncompliant(data.getOwnerIdAddress()), null));
        personalRuleList.add(new ValidateRule<>("334", "已售-个人用户-未登记购车用户开通非定向功能", IovCardValidator::isUnregisterNondirectFunction, UNREGISTER));
        personalRuleList.add(new ValidateRule<>("335", "已售-个人用户-未登记车辆信息", IovCardValidator::isUnregisterVehicleInfo, UNREGISTER));
        personalRuleList.add(new ValidateRule<>("336", "已售-个人用户-语音限制类型登记错误",
            data -> isLimitTypeRegisterError(data, VOICE_LIMIT_TYPE, IovCardEntity::getVoiceEnableStatus, IovCardEntity::getVoiceLimitType), NONCOMPLIANT));
        personalRuleList.add(new ValidateRule<>("337", "已售-个人用户-语音定向数量登记错误", data -> isDirectNumRegisterError(data, IovCardEntity::getVoiceEnableStatus,
            IovCardEntity::getVoiceLimitType, IovCardEntity::getVoiceDirectNum, DIRECTIONAL), NONCOMPLIANT));
        personalRuleList.add(new ValidateRule<>("338", "已售-个人用户-定向语音白名单超限", data -> isDirectNumOverLimit(data, VOICE_DIRECT_NUM_KEY,
            IovCardEntity::getVoiceEnableStatus, IovCardEntity::getVoiceLimitType, IovCardEntity::getVoiceDirectNum, DIRECTIONAL), null));
        personalRuleList.add(new ValidateRule<>("339", "已售-个人用户-短信限制类型登记错误",
            data -> isLimitTypeRegisterError(data, SMS_LIMIT_TYPE, IovCardEntity::getSmsEnableStatus, IovCardEntity::getSmsLimitType), NONCOMPLIANT));
        personalRuleList.add(new ValidateRule<>("340", "已售-个人用户-短信定向数量登记错误", data -> isDirectNumRegisterError(data, IovCardEntity::getSmsEnableStatus,
            IovCardEntity::getSmsLimitType, IovCardEntity::getSmsDirectNum, DIRECTIONAL), NONCOMPLIANT));
        personalRuleList.add(new ValidateRule<>("341", "已售-个人用户-定向短信白名单超限", data -> isDirectNumOverLimit(data, SMS_DIRECT_NUM_KEY,
            IovCardEntity::getSmsEnableStatus, IovCardEntity::getSmsLimitType, IovCardEntity::getSmsDirectNum, DIRECTIONAL), null));
        personalRuleList.add(new ValidateRule<>("342", "已售-个人用户-流量限制登记错误",
            data -> isLimitTypeRegisterError(data, TRAFFIC_LIMIT_TYPE, IovCardEntity::getTrafficEnableStatus, IovCardEntity::getTrafficLimitType),
            NONCOMPLIANT));
        personalRuleList.add(new ValidateRule<>("343", "已售-个人用户-定向流量数量登记错误", data -> isDirectNumRegisterError(data, IovCardEntity::getTrafficEnableStatus,
            IovCardEntity::getTrafficLimitType, IovCardEntity::getTrafficDirectNum, DIRECTIONAL_TRAFFIC_LIMIT), NONCOMPLIANT));
        personalRuleList.add(new ValidateRule<>("344", "已售-个人用户-定向流量白名单超限", data -> isDirectNumOverLimit(data, TRAFFIC_DIRECT_NUM_KEY,
            IovCardEntity::getTrafficEnableStatus, IovCardEntity::getTrafficLimitType, IovCardEntity::getTrafficDirectNum, DIRECTIONAL_TRAFFIC_LIMIT), null));

        companyRuleList.add(new ValidateRule<>("345", "已售-单位用户-购卡渠道类型不合规", data -> isDictIncorrect(IOVCARD_CHANNEL_TYPE, data.getChannelType()), NONCOMPLIANT));
        companyRuleList.add(new ValidateRule<>("346", "已售-单位用户-购卡单位信息未登记", IovCardValidator::isCompanyUnregister, UNREGISTER));
        companyRuleList.add(new ValidateRule<>("347", "已售-单位用户-购卡责任人信息未登记", IovCardValidator::isPicUnregister, UNREGISTER));
        companyRuleList.add(new ValidateRule<>("348", "已售-单位用户-购卡经办人未登记", IovCardValidator::isAgentUnregister, UNREGISTER));
        companyRuleList.add(new ValidateRule<>("349", "已售-单位用户-购卡责任人&单位信息未登记", data -> isCompanyUnregister(data) && isPicUnregister(data), null));
        companyRuleList.add(new ValidateRule<>("350", "已售-单位用户-购卡责任人&经办人信息未登记", data -> isPicUnregister(data) && isAgentUnregister(data), null));
        companyRuleList.add(new ValidateRule<>("351", "已售-单位用户-购卡单位&经办人信息未登记", data -> isCompanyUnregister(data) && isAgentUnregister(data), null));
        companyRuleList.add(new ValidateRule<>("352", "已售-单位用户-购卡责任人&单位&经办人信息未登记",
            data -> isPicUnregister(data) && isCompanyUnregister(data) && isAgentUnregister(data), null));
        companyRuleList.add(new ValidateRule<>("353", "已售-单位用户-单位信息校验不合规", IovCardValidator::isCompanyNoncompliant, NONCOMPLIANT));
        companyRuleList.add(new ValidateRule<>("354", "已售-单位用户-购卡责任人信息校验不合规", IovCardValidator::isPicNoncompliant, NONCOMPLIANT));
        companyRuleList.add(new ValidateRule<>("355", "已售-单位用户-购卡经办人信息检验不合规", IovCardValidator::isAgentNoncompliant, NONCOMPLIANT));
        companyRuleList.add(new ValidateRule<>("356", "已售-单位用户-购卡责任人&单位信息校验不合规", data -> isPicNoncompliant(data) && isCompanyNoncompliant(data), null));
        companyRuleList.add(new ValidateRule<>("357", "已售-单位用户-购卡责任人&经办人信息校验不合规", data -> isPicNoncompliant(data) && isAgentNoncompliant(data), null));
        companyRuleList.add(new ValidateRule<>("358", "已售-单位用户-购卡单位&经办人信息校验不合规", data -> isCompanyNoncompliant(data) && isAgentNoncompliant(data), null));
        companyRuleList.add(new ValidateRule<>("359", "已售-单位用户-购卡责任人&单位&经办人信息校验不合规",
            data -> isPicNoncompliant(data) && isCompanyNoncompliant(data) && isAgentNoncompliant(data), null));
        companyRuleList.add(new ValidateRule<>("360", "已售-单位用户-未登记车辆信息", IovCardValidator::isUnregisterVehicleInfo, UNREGISTER));
        companyRuleList.add(new ValidateRule<>("361", "已售-单位用户-未登记购车用户开通非定向功能", IovCardValidator::isUnregisterNondirectFunction, UNREGISTER));
        companyRuleList.add(new ValidateRule<>("362", "已售-单位用户-语音限制类型登记错误",
            data -> isLimitTypeRegisterError(data, VOICE_LIMIT_TYPE, IovCardEntity::getVoiceEnableStatus, IovCardEntity::getVoiceLimitType), NONCOMPLIANT));
        companyRuleList.add(new ValidateRule<>("363", "已售-单位用户-语音定向数量登记错误", data -> isDirectNumRegisterError(data, IovCardEntity::getVoiceEnableStatus,
            IovCardEntity::getVoiceLimitType, IovCardEntity::getVoiceDirectNum, DIRECTIONAL), null));
        companyRuleList.add(new ValidateRule<>("364", "已售-单位用户-定向语音白名单超限", data -> isDirectNumOverLimit(data, VOICE_DIRECT_NUM_KEY,
            IovCardEntity::getVoiceEnableStatus, IovCardEntity::getVoiceLimitType, IovCardEntity::getVoiceDirectNum, DIRECTIONAL), null));
        companyRuleList.add(new ValidateRule<>("365", "已售-单位用户-短信限制类型登记错误",
            data -> isLimitTypeRegisterError(data, SMS_LIMIT_TYPE, IovCardEntity::getSmsEnableStatus, IovCardEntity::getSmsLimitType), NONCOMPLIANT));
        companyRuleList.add(new ValidateRule<>("366", "已售-单位用户-短信定向数量登记错误", data -> isDirectNumRegisterError(data, IovCardEntity::getSmsEnableStatus,
            IovCardEntity::getSmsLimitType, IovCardEntity::getSmsDirectNum, DIRECTIONAL), NONCOMPLIANT));
        companyRuleList.add(new ValidateRule<>("367", "已售-单位用户-定向短信白名单超限", data -> isDirectNumOverLimit(data, SMS_DIRECT_NUM_KEY,
            IovCardEntity::getSmsEnableStatus, IovCardEntity::getSmsLimitType, IovCardEntity::getSmsDirectNum, DIRECTIONAL), null));
        companyRuleList.add(new ValidateRule<>("368", "已售-单位用户-流量限制登记错误",
            data -> isLimitTypeRegisterError(data, TRAFFIC_LIMIT_TYPE, IovCardEntity::getTrafficEnableStatus, IovCardEntity::getTrafficLimitType),
            NONCOMPLIANT));
        companyRuleList.add(new ValidateRule<>("369", "已售-单位用户-定向流量数量登记错误", data -> isDirectNumRegisterError(data, IovCardEntity::getTrafficEnableStatus,
            IovCardEntity::getTrafficLimitType, IovCardEntity::getTrafficDirectNum, DIRECTIONAL_TRAFFIC_LIMIT), NONCOMPLIANT));
        companyRuleList.add(new ValidateRule<>("370", "已售-单位用户-定向流量白名单超限", data -> isDirectNumOverLimit(data, TRAFFIC_DIRECT_NUM_KEY,
            IovCardEntity::getTrafficEnableStatus, IovCardEntity::getTrafficLimitType, IovCardEntity::getTrafficDirectNum, DIRECTIONAL_TRAFFIC_LIMIT), null));
    }

    @Override
    public void inspect(InspectRecordEntity inspectRecord, String importFilePath) {
        int inspectRecordId = inspectRecord.getId();
        String reportFileDir = inspectRecord.getReportFileDir();
        try {
            List<ValidateRule<IovCardEntity>> enableCommonRules = listEnableValidateRule(commonRuleList, IOV_CARD);
            List<ValidateRule<IovCardEntity>> enablePersonalRules = listEnableValidateRule(personalRuleList, IOV_CARD);
            List<ValidateRule<IovCardEntity>> enableCompanyRules = listEnableValidateRule(companyRuleList, IOV_CARD);
            BufferedReader reader = null;
            String line;
            List<String> filedList;
            List<String> fieldExceptionList = new ArrayList<>();
            Map<String, List<IovCardEntity>> codeEntityMap = new TreeMap<>();
            // 总量
            int totalNum = 0;
            IovCardStatDTO iovCardStatDTO = new IovCardStatDTO();
            try {
                reader = FileUtil.getReader(new File(importFilePath), CHARSET_GBK);
                while (true) {
                    line = reader.readLine();
                    if (StrUtil.isBlank(line)) {
                        break;
                    }
                    totalNum++;
                    filedList = StrUtil.split(line, "||");
                    if (filedList.size() != IOC_CARD_FIELD_NUM) {
                        fieldExceptionList.add(line);
                        continue;
                    }
                    // 未登记标识
                    boolean unregisterFlag = false;
                    // 不合规标识
                    boolean noncomplaianceFlag = false;
                    // 公共校验规则标识
                    boolean commonRuleComplianceFlag = true;
                    // 个人用户合规标识
                    boolean personalComplianceFlag = true;
                    // 单位用户-合规标识
                    boolean companyComplianceFlag = true;
                    IovCardEntity personalUser = OperatorObjectUtil.createObj(filedList, IovCardEntity.class);
                    // 公共校验规则
                    for (ValidateRule<IovCardEntity> validateRule : enableCommonRules) {
                        if (validateRule.getValidate().test(personalUser)) {
                            commonRuleComplianceFlag = false;
                            codeEntityMap.computeIfAbsent(validateRule.getRuleCode(), key -> ListUtil.list(false)).add(personalUser);
                        }
                    }
                    if (PERSONAL.equals(personalUser.getUserType())) {
                        for (ValidateRule<IovCardEntity> validateRule : enablePersonalRules) {
                            if (validateRule.getValidate().test(personalUser)) {
                                codeEntityMap.computeIfAbsent(validateRule.getRuleCode(), key -> ListUtil.list(false)).add(personalUser);
                                // 只要有一个匹配上，那就不是合规的
                                personalComplianceFlag = false;
                                if (UNREGISTER == validateRule.getType()) {
                                    unregisterFlag = true;
                                } else if (NONCOMPLIANT == validateRule.getType()) {
                                    noncomplaianceFlag = true;
                                }
                            }
                        }
                    } else if (COMPANY.equals(personalUser.getUserType())) {
                        for (ValidateRule<IovCardEntity> validateRule : enableCompanyRules) {
                            if (validateRule.getValidate().test(personalUser)) {
                                codeEntityMap.computeIfAbsent(validateRule.getRuleCode(), key -> ListUtil.list(false)).add(personalUser);
                                // 只要有一个匹配上，那就不是合规的
                                companyComplianceFlag = false;
                                if (UNREGISTER == validateRule.getType()) {
                                    unregisterFlag = true;
                                } else if (NONCOMPLIANT == validateRule.getType()) {
                                    noncomplaianceFlag = true;
                                }
                            }
                        }
                    }
                    // 只要是未登记或者不合规，那么肯定不属于合规了，因为合规的要求是该类型所有的不合规项都匹配不上
                    if (unregisterFlag || noncomplaianceFlag) {
                        if (unregisterFlag) {
                            iovCardStatDTO.getUnregisterList().add(personalUser);
                        }
                        if (noncomplaianceFlag) {
                            iovCardStatDTO.getNoncompliantList().add(personalUser);
                        }
                    } else {
                        // 通用校验规则必须也为true，才有合规的可能性
                        if (commonRuleComplianceFlag) {
                            if (PERSONAL.equals(personalUser.getUserType()) && personalComplianceFlag) {
                                iovCardStatDTO.getPersonalList().add(personalUser);
                            } else if (COMPANY.equals(personalUser.getUserType()) && companyComplianceFlag) {
                                iovCardStatDTO.getCompanyList().add(personalUser);
                            }
                        }
                    }
                }
            } catch (IOException exception) {
                log.error("车联网卡实名制检查失败，读取文件内容异常", exception);
                operatorInspectService.deleteImportData(IOV_CARD.getType(), inspectRecord.getImportRecordId());
                inspectRecordService.updateStatusAndFinishTime(inspectRecordId, FAILED);
                throw exception;
            } finally {
                IoUtil.close(reader);
            }
            // 启用的校验规则code
            List<String> enableCodeList = GlobalVariables.getTypeCodeMap().get(IOV_CARD.getType());
            Map<String, String> codeNameMap = GlobalVariables.getCodeNameMap();
            List<InspectReportEntity> inspectReportList = new ArrayList<>();
            // 统计map
            Map<String, Integer> statisticsMap = new LinkedHashMap<>();
            statisticsMap.put("检查总量", totalNum);
            if (enableCodeList.contains(IOV_CARD_FORMAT_EXCEPTION_CODE)) {
                statisticsMap.put("格式异常数据量",
                    !codeEntityMap.containsKey(IOV_CARD_FORMAT_EXCEPTION_CODE) ? 0 : codeEntityMap.get(IOV_CARD_FORMAT_EXCEPTION_CODE).size());
            }
            // 是否校验字段异常
            if (enableCodeList.contains(IOV_CARD_FIELD_EXCEPTION_CODE)) {
                statisticsMap.put("字段异常数据量", fieldExceptionList.size());
                if (CollUtil.isNotEmpty(fieldExceptionList)) {
                    String fileName = codeNameMap.getOrDefault(IOV_CARD_FIELD_EXCEPTION_CODE, "字段异常数据") + ".txt";
                    // 完整路径为./reportFile/yyyyMMddHHmmss/字段异常数据.txt
                    FileUtil.writeUtf8Lines(fieldExceptionList, new File(reportFileDir + fileName));
                    InspectReportEntity inspectReportEntity =
                        InspectReportEntity.builder().fileName(fileName).recordId(inspectRecordId).generateTime(LocalDateTime.now()).build();
                    inspectReportList.add(inspectReportEntity);
                }
            }
            statisticsMap.put("未登记总量", iovCardStatDTO.getUnregisterList().size());
            statisticsMap.put("不合规总量", iovCardStatDTO.getNoncompliantList().size());
            statisticsMap.put("全量合规量", iovCardStatDTO.getCompliantList().size());
            statisticsMap.put("个人用户-合规量", iovCardStatDTO.getPersonalList().size());
            statisticsMap.put("单位用户-合规量", iovCardStatDTO.getCompanyList().size());
            // 一证十号
            if (enableCodeList.contains(ONE_CARD_TEN_NUMBER_CODE)) {
                List<IovCardEntity> oneCardTenNumbersList = iovCardService.listOneCardTenNumbers();
                codeEntityMap.put(ONE_CARD_TEN_NUMBER_CODE, oneCardTenNumbersList);
            }
            // 遍历启用的校验规则
            enableCodeList.forEach(ruleCode -> {
                // 格式异常、字段异常上边已经处理过了
                if (IOV_CARD_FORMAT_EXCEPTION_CODE.equals(ruleCode) || IOV_CARD_FIELD_EXCEPTION_CODE.equals(ruleCode)) {
                    return;
                }
                // 如果codeEntityMap没有该校验规则code，表示该校验规则虽然启用了但是没有符合条件的数据
                if (!codeEntityMap.containsKey(ruleCode)) {
                    statisticsMap.put(codeNameMap.get(ruleCode), 0);
                } else {
                    statisticsMap.put(codeNameMap.get(ruleCode), codeEntityMap.get(ruleCode).size());
                }
            });
            genreateFixedTermsExcel(statisticsMap, reportFileDir, inspectRecordId, inspectReportList, iovCardStatDTO);
            // 开始循环生成excel文件
            codeEntityMap.forEach((key, value) -> {
                if (CollectionUtil.isEmpty(value)) {
                    return;
                }
                // 完整路径为./reportFile/yyyyMMddHHmmss/校验规则名称.xlsx
                String fileName = codeNameMap.get(key) + ExcelTypeEnum.XLSX.getValue();
                String fullPath = reportFileDir + fileName;
                desensitizeIovCard(value);
                ExcelUtil.writeMultipleSheet(fullPath, IovCardEntity.class, codeNameMap.get(key), value);
                inspectReportList.add(InspectReportEntity.builder().fileName(fileName).recordId(inspectRecordId).generateTime(LocalDateTime.now()).build());
            });
            inspectReportService.saveBatch(inspectReportList);
        } catch (Exception exception) {
            log.error("车联网卡实名制检查失败", exception);
            operatorInspectService.deleteImportData(IOV_CARD.getType(), inspectRecord.getImportRecordId());
            FileUtil.del(new File(reportFileDir));
            inspectRecordService.updateStatusAndFinishTime(inspectRecordId, FAILED);
            throw new BusinessException(exception);
        }
    }

    /**
     * @Description 生成固定项excel文件
     * @Auhtor 连新景
     * @Date 2024/08/13 17:41
     * @param statisticsMap
     * @param reportFileDir
     * @param inspectRecordId
     * @param inspectReportList
     * @param IovCardStatDTO
     */
    private void genreateFixedTermsExcel(Map<String, Integer> statisticsMap, String reportFileDir, Integer inspectRecordId,
        List<InspectReportEntity> inspectReportList, IovCardStatDTO IovCardStatDTO) {
        // 生成检查统计表
        List<List<Object>> statisticsList = new ArrayList<>(statisticsMap.size());
        statisticsMap.forEach((key, value) -> {
            List<Object> data = new ArrayList<>(2);
            data.add(key);
            data.add(value);
            statisticsList.add(data);
        });
        EasyExcel.write(reportFileDir + "检查统计表.xlsx").registerWriteHandler(new InspectStatColumnWidthStyleStrategy()).sheet("检查统计表").doWrite(statisticsList);
        InspectReportEntity inspectReportEntity =
            InspectReportEntity.builder().fileName("检查统计表.xlsx").recordId(inspectRecordId).generateTime(LocalDateTime.now()).build();
        inspectReportList.add(inspectReportEntity);
        // 生成固定明细项
        if (CollectionUtil.isNotEmpty(IovCardStatDTO.getUnregisterList())) {
            desensitizeIovCard(IovCardStatDTO.getUnregisterList());
            ExcelUtil.writeMultipleSheet(reportFileDir + "未登记数据.xlsx", IovCardEntity.class, "未登记数据", IovCardStatDTO.getUnregisterList());
            inspectReportEntity = InspectReportEntity.builder().fileName("未登记数据.xlsx").recordId(inspectRecordId).generateTime(LocalDateTime.now()).build();
            inspectReportList.add(inspectReportEntity);
        }
        if (CollectionUtil.isNotEmpty(IovCardStatDTO.getNoncompliantList())) {
            desensitizeIovCard(IovCardStatDTO.getNoncompliantList());
            ExcelUtil.writeMultipleSheet(reportFileDir + "不合规数据.xlsx", IovCardEntity.class, "不合规数据", IovCardStatDTO.getNoncompliantList());
            inspectReportEntity = InspectReportEntity.builder().fileName("不合规数据.xlsx").recordId(inspectRecordId).generateTime(LocalDateTime.now()).build();
            inspectReportList.add(inspectReportEntity);
        }
        if (CollectionUtil.isNotEmpty(IovCardStatDTO.getCompliantList())) {
            desensitizeIovCard(IovCardStatDTO.getCompliantList());
            ExcelUtil.writeMultipleSheet(reportFileDir + "全量合规数据.xlsx", IovCardEntity.class, "全量合规数据", IovCardStatDTO.getCompliantList());
            inspectReportEntity = InspectReportEntity.builder().fileName("全量合规数据.xlsx").recordId(inspectRecordId).generateTime(LocalDateTime.now()).build();
            inspectReportList.add(inspectReportEntity);
        }
        if (CollectionUtil.isNotEmpty(IovCardStatDTO.getPersonalList())) {
            desensitizeIovCard(IovCardStatDTO.getPersonalList());
            ExcelUtil.writeMultipleSheet(reportFileDir + "个人用户-合规数据.xlsx", IovCardEntity.class, "个人用户-合规数据", IovCardStatDTO.getPersonalList());
            inspectReportEntity = InspectReportEntity.builder().fileName("个人用户-合规数据.xlsx").recordId(inspectRecordId).generateTime(LocalDateTime.now()).build();
            inspectReportList.add(inspectReportEntity);
        }
        if (CollectionUtil.isNotEmpty(IovCardStatDTO.getCompanyList())) {
            desensitizeIovCard(IovCardStatDTO.getCompanyList());
            ExcelUtil.writeMultipleSheet(reportFileDir + "单位用户-合规数据.xlsx", IovCardEntity.class, "单位用户-合规数据", IovCardStatDTO.getCompanyList());
            inspectReportEntity = InspectReportEntity.builder().fileName("单位用户-合规数据.xlsx").recordId(inspectRecordId).generateTime(LocalDateTime.now()).build();
            inspectReportList.add(inspectReportEntity);
        }
    }

}
